/**
 * 将包含parentId的flat结构数组,转换为携带children属性的树形结构数组
 * @param {array} ary
 * @returns 树形数组
 */
export function flatToTree(ary, key = 'itemId') {
  const map = new Map();
  const roots = [];

  for (const item of ary) {
    map.set(item[key], item);
  }

  for (const item of ary) {
    const parent = map.get(item.parentId);
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(item);
    } else {
      roots.push(item);
    }
  }

  return roots;
}

/**
 * 计算多个数组里相同下标的和
 * @param {array} ary
 * @returns 树形数组
 */
export function sumArrays(arrays, key) {
  if (arrays.length === 0 || arrays[0].length === 0) return [];
  const { length } = arrays[0];
  // 初始化第一个数据
  const result = new Array(length).fill(0);
  arrays.forEach((arr) => {
    for (let i = 0; i < length; i++) {
      result[i] += key ? Number(arr[i][key]) : Number(arr[i]);
    }
  });
  return result;
}
